// 获取dom元素
const tbody = document.querySelector('tbody');
const addModal = document.querySelector('#openModal');
const modal = new bootstrap.Modal(document.querySelector('#modal')) //模态框
const province = document.querySelector('select[name=province]');       //省市区
const city = document.querySelector('select[name=city]');       //省市区
const area = document.querySelector('select[name=area]');       //省市区
const title = document.querySelector('.modal-title');      //模态框标题
const submit = document.querySelector('#submit');           //提交表单
const form = document.querySelector('form');
// let id  //全局变量

async function initStudent() {
    const res = await axios({
        url: '/students',
        method: 'get',
    })
    // console.log(res.data.data);
    const html = res.data.data.reduce((init, item, index) => {
        // console.log(item);
        let { id, age, name, gender, group, hope_salary, salary, province, city, area } = item
        // 一共有多少位学生
        document.querySelector('.total').innerHTML = index + 1;

        // console.log(gender === 1);
        return init += `<tr>
        <td>${name}</td>
        <td>${age}</td>
        <td>${gender == 1 ? '男' : '女'}</td>
        <td>${group}组</td>
        <td>${hope_salary}</td>
        <td>${salary}</td>
        <td>${province + city + area}</td>
        <td>
            <a href="javascript:;" class="text-success mr-3">
                <i data-id="${id}" class="bi bi-pen editBtn"></i>
            </a>
            <a  href="javascript:;" class="text-danger">
              <i data-id="${id}" class="bi bi-trash deleteBtn"></i>
            </a>
        </td>
        </tr>`
    }, '')
    document.querySelector('.list').innerHTML = html;
}

initStudent();

// 获得 省
getSelect('/api/province', {}, province, '省份')

// 获取  市
// 获取 区
async function getSelect(url, params, target, targetName) {
    const res = await axios({
        url,
        params
    })
    const html = res.data.data.reduce((init, item) => {
        return init + `
        <option value="${item}">${item}</option>
        `
    }, `<option value="">--${targetName}--</option>`)
    target.innerHTML = html
}
// 改变省，输出市
province.addEventListener('change', async e => {
    await getSelect('/api/city', { pname: province.value }, city, '城市')
    // await getSelect('/api/area', { pname: province.value, cname: city.value }, area, '地区')
    area.innerHTML = `<option value>--区--</option>`
})
// 改变市 输出区
city.addEventListener('change', async e => {
    await getSelect('/api/area', { pname: province.value, cname: city.value }, area, '区')

})



// 提交模态框表单
form.addEventListener('submit', async e => {
    e.preventDefault()
    const data = serialize(form, { hash: true, empty: true })
    const id = data.id
    delete data.id
    for (const key in data) {
        if (!data[key]) {
            bsShow('请输入内容')
        }
    }
    data.age = +data.age;
    data.gender = +data.gender;
    data.salary = +data.salary;
    data.hope_salary = +data.hope_salary;
    data.group = +data.group;
    let result
    if (title.innerHTML === '添加学员') {
        result = await axios({
            url: '/students',
            method: 'post',
            data
        })
    } else if (title.innerHTML === '编辑学员') {
        result = await axios({
            url: `/students/${id}`,
            method: 'put',
            data
        })
    }
    modal.hide()
    form.reset();
    bsShow('操作成功')
    initStudent()
    //  (data)    
})

// 打开模态框,添加学生
addModal.addEventListener('click', function (e) {
    modal.show();
    title.innerText = '添加学员';
})

// 编辑 事件委托
tbody.addEventListener('click', async function (e) {
    const target = e.target
    if (target.classList.contains("editBtn")) {
        modal.show();
        title.innerText = '编辑学员';
        const id = target.dataset.id
        console.log(id);
        const res = await axios({
            url: `/students/${id}`,
        })

        const obj = res.data.data
        await getSelect('/api/city', { pname: obj.province }, city, '城市')
        await getSelect('/api/area', { pname: obj.province, cname: obj.city }, area, '地区')

        for (const key in obj) {
            const formEle = document.querySelector(`[name=${key}]`);
            if (formEle && key !== "gender") {
                formEle.value = obj[key]
            }
        }
        document.querySelector(`[name="gender"][value="${obj.gender}"]`).checked = true;
        // obj.gender === 1 ? document.querySelector('#cb02').checked = true : document.querySelector('#cb01').checked = true
    } else if (target.classList.contains('deleteBtn')) {
        const id = target.dataset.id
        const res = await axios({
            url: `/students/${id}`,
            method: 'delete'
        })
        bsShow('恭喜，删除成功！！！')
        initStudent();
    }
})